package com.example.launibleplugin.manager

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice as AndroidBluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothManager as AndroidBluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.core.app.ActivityCompat
import com.example.launibleplugin.constants.BluetoothConstants
import com.example.launibleplugin.listener.BluetoothEventListener
import com.example.launibleplugin.model.BluetoothDevice
import com.example.launibleplugin.model.ConnectionInfo
import com.example.launibleplugin.model.ConnectionState
import com.example.launibleplugin.model.DataRecord
import com.example.launibleplugin.parser.DataParser
import com.example.launibleplugin.protocol.RespiratoryProtocolHandler
import com.example.launibleplugin.protocol.HandshakeMessage
import com.example.launibleplugin.protocol.DataReportMessage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap

/**
 * 蓝牙管理器
 * Function: 管理蓝牙设备的扫描、连接和数据通信
 * Parameter: context - Android上下文
 * Note: 核心蓝牙操作管理类，支持BLE设备通信
 */
class BluetoothManager(private val context: Context) {
    
    companion object {
        private const val TAG = BluetoothConstants.LOG_TAG_BLUETOOTH
        private const val CLIENT_CHARACTERISTIC_CONFIG_UUID = "00002902-0000-1000-8000-00805f9b34fb"
        
        // 标准蓝牙服务UUID列表
        private val STANDARD_BLUETOOTH_SERVICES = setOf(
            "00001800-0000-1000-8000-00805f9b34fb", // Generic Access
            "00001801-0000-1000-8000-00805f9b34fb", // Generic Attribute
            "0000180a-0000-1000-8000-00805f9b34fb", // Device Information
            "0000180f-0000-1000-8000-00805f9b34fb", // Battery Service
            "00001802-0000-1000-8000-00805f9b34fb", // Immediate Alert
            "00001803-0000-1000-8000-00805f9b34fb", // Link Loss
            "00001804-0000-1000-8000-00805f9b34fb", // Tx Power
            "00001805-0000-1000-8000-00805f9b34fb", // Current Time Service
            "00001806-0000-1000-8000-00805f9b34fb", // Reference Time Update Service
            "00001807-0000-1000-8000-00805f9b34fb", // Next DST Change Service
            "00001808-0000-1000-8000-00805f9b34fb", // Glucose
            "00001809-0000-1000-8000-00805f9b34fb", // Health Thermometer
            "0000180d-0000-1000-8000-00805f9b34fb", // Heart Rate
            "0000180e-0000-1000-8000-00805f9b34fb", // Phone Alert Status Service
            "00001810-0000-1000-8000-00805f9b34fb", // Blood Pressure
            "00001811-0000-1000-8000-00805f9b34fb", // Alert Notification Service
            "00001812-0000-1000-8000-00805f9b34fb", // Human Interface Device
            "00001813-0000-1000-8000-00805f9b34fb", // Scan Parameters
            "00001814-0000-1000-8000-00805f9b34fb", // Running Speed and Cadence
            "00001815-0000-1000-8000-00805f9b34fb", // Automation IO
            "00001816-0000-1000-8000-00805f9b34fb", // Cycling Speed and Cadence
            "00001818-0000-1000-8000-00805f9b34fb", // Cycling Power
            "00001819-0000-1000-8000-00805f9b34fb", // Location and Navigation
            "0000181a-0000-1000-8000-00805f9b34fb", // Environmental Sensing
            "0000181b-0000-1000-8000-00805f9b34fb", // Body Composition
            "0000181c-0000-1000-8000-00805f9b34fb", // User Data
            "0000181d-0000-1000-8000-00805f9b34fb", // Weight Scale
            "0000181e-0000-1000-8000-00805f9b34fb", // Bond Management
            "0000181f-0000-1000-8000-00805f9b34fb", // Continuous Glucose Monitoring
            "00001820-0000-1000-8000-00805f9b34fb", // Internet Protocol Support
            "00001821-0000-1000-8000-00805f9b34fb", // Indoor Positioning
            "00001822-0000-1000-8000-00805f9b34fb", // Pulse Oximeter
            "00001823-0000-1000-8000-00805f9b34fb", // HTTP Proxy
            "00001824-0000-1000-8000-00805f9b34fb", // Transport Discovery
            "00001825-0000-1000-8000-00805f9b34fb", // Object Transfer
            "00001826-0000-1000-8000-00805f9b34fb", // Fitness Machine
            "00001827-0000-1000-8000-00805f9b34fb", // Mesh Provisioning
            "00001828-0000-1000-8000-00805f9b34fb", // Mesh Proxy
            "00001829-0000-1000-8000-00805f9b34fb", // Reconnection Configuration
            "0000fe59-0000-1000-8000-00805f9b34fb"  // Google
        )
        
        /**
         * Function: 判断是否为标准蓝牙服务
         * Parameter: serviceUuid - 服务UUID字符串
         * Return: Boolean - 是否为标准服务
         * Note: 用于区分标准服务和自定义服务
         */
        private fun isStandardBluetoothService(serviceUuid: String): Boolean {
            return STANDARD_BLUETOOTH_SERVICES.contains(serviceUuid.lowercase())
        }
    }
    
    // 蓝牙适配器和扫描器
    private val bluetoothManager: AndroidBluetoothManager = 
        context.getSystemService(Context.BLUETOOTH_SERVICE) as AndroidBluetoothManager
    private val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.adapter
    private val bluetoothLeScanner: BluetoothLeScanner? = bluetoothAdapter?.bluetoothLeScanner
    
    // 数据解析器
    private val dataParser = DataParser()
    
    // 呼吸家协议处理器
    private val protocolHandler = RespiratoryProtocolHandler()
    
    // 事件监听器
    private var eventListener: BluetoothEventListener? = null
    
    // 握手状态管理
    private val handshakeStatus = ConcurrentHashMap<String, Boolean>()
    private val handshakeJobs = ConcurrentHashMap<String, Job>()
    
    // 扫描相关
    private var isScanning = false
    private val scanHandler = Handler(Looper.getMainLooper())
    private var scanTimeoutJob: Job? = null
    private val discoveredDevices = mutableMapOf<String, BluetoothDevice>()
    
    // 连接管理
    private val connectedDevices = ConcurrentHashMap<String, BluetoothGatt>()
    private val connectionInfoMap = ConcurrentHashMap<String, ConnectionInfo>()
    private val coroutineScope = CoroutineScope(Dispatchers.Main + Job())
    
    /**
     * Function: 设置事件监听器
     * Parameter: listener - 蓝牙事件监听器
     * Note: 设置回调监听器以接收蓝牙事件通知
     */
    fun setEventListener(listener: BluetoothEventListener) {
        this.eventListener = listener
    }
    
    /**
     * Function: 检查蓝牙是否可用
     * Return: Boolean - 蓝牙是否可用
     * Note: 检查设备是否支持蓝牙且蓝牙已启用
     */
    fun isBluetoothAvailable(): Boolean {
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled
    }
    
    /**
     * Function: 检查是否有必要的权限
     * Return: Boolean - 是否有所需权限
     * Note: 检查蓝牙和位置权限
     */
    fun hasRequiredPermissions(): Boolean {
        val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            BluetoothConstants.BLUETOOTH_PERMISSIONS_API31
        } else {
            BluetoothConstants.BLUETOOTH_PERMISSIONS
        }
        
        return permissions.all { permission ->
            ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
        }
    }
    
    /**
     * Function: 开始扫描蓝牙设备
     * Parameter: timeoutMs - 扫描超时时间（毫秒）
     * Parameter: deviceNameFilter - 设备名称过滤器（可选）
     * Note: 开始BLE设备扫描，支持设备名称过滤
     */
    fun startScan(timeoutMs: Long = BluetoothConstants.SCAN_TIMEOUT_MS, deviceNameFilter: String? = null) {
        if (!isBluetoothAvailable()) {
            eventListener?.onScanFailed(-1, "蓝牙不可用")
            return
        }
        
        if (!hasRequiredPermissions()) {
            eventListener?.onScanFailed(-2, "缺少必要权限")
            return
        }
        
        if (isScanning) {
            Log.w(TAG, "扫描已在进行中")
            return
        }
        
        try {
            discoveredDevices.clear()
            isScanning = true
            
            // 配置扫描设置
            val scanSettings = ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                .build()
            
            // 配置扫描过滤器
            val scanFilters = mutableListOf<ScanFilter>()
            deviceNameFilter?.let { filter ->
                scanFilters.add(
                    ScanFilter.Builder()
                        .setDeviceName(filter)
                        .build()
                )
            }
            
            // 开始扫描
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "开始扫描蓝牙设备，超时时间: ${timeoutMs}ms, 过滤器数量: ${scanFilters.size}")
                bluetoothLeScanner?.startScan(scanFilters, scanSettings, scanCallback)
                eventListener?.onScanStarted()
                
                // 设置扫描超时
                scanTimeoutJob = coroutineScope.launch {
                    delay(timeoutMs)
                    Log.i(TAG, "扫描超时，自动停止扫描")
                    stopScan()
                }
                
                Log.d(TAG, "蓝牙扫描已启动，等待设备发现...")
            } else {
                Log.e(TAG, "缺少BLUETOOTH_SCAN权限，无法启动扫描")
                eventListener?.onScanFailed(-2, "缺少BLUETOOTH_SCAN权限")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "启动扫描失败", e)
            isScanning = false
            eventListener?.onScanFailed(-3, "启动扫描失败: ${e.message}")
        }
    }
    
    /**
     * Function: 停止扫描
     * Note: 停止BLE设备扫描并通知结果
     */
    fun stopScan() {
        if (!isScanning) {
            return
        }
        
        try {
            scanTimeoutJob?.cancel()
            
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
                bluetoothLeScanner?.stopScan(scanCallback)
            }
            
            isScanning = false
            
            val deviceList = discoveredDevices.values.toList()
            eventListener?.onScanCompleted(deviceList)
            
            Log.i(TAG, "扫描完成，发现 ${deviceList.size} 个设备")
            deviceList.forEach { device ->
                Log.d(TAG, "  - ${device.getDisplayName()} (${device.macAddress}) RSSI: ${device.signalStrength}")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "停止扫描失败", e)
            eventListener?.onScanFailed(-4, "停止扫描失败: ${e.message}")
        }
    }
    
    /**
     * 扫描回调
     */
    private val scanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            try {
                val device = result.device
                val rssi = result.rssi
                
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                    val deviceName = device.name
                    val macAddress = device.address
                    
                    // 添加详细的扫描日志
                    Log.d(TAG, "扫描到设备: 名称='$deviceName', MAC='$macAddress', RSSI=$rssi")
                    
                    // 暂时移除设备过滤，发现所有设备进行调试
                    val bluetoothDevice = BluetoothDevice(
                        deviceId = macAddress,
                        deviceName = deviceName,
                        macAddress = macAddress,
                        signalStrength = rssi,
                        lastSeen = System.currentTimeMillis()
                    )
                    
                    // 检查是否已存在，避免重复添加
                    if (!discoveredDevices.containsKey(macAddress)) {
                        discoveredDevices[macAddress] = bluetoothDevice
                        eventListener?.onDeviceFound(bluetoothDevice)
                        Log.i(TAG, "新发现设备: $deviceName ($macAddress), RSSI: $rssi")
                    } else {
                        // 更新信号强度
                        discoveredDevices[macAddress]?.signalStrength = rssi
                        Log.v(TAG, "更新设备信号: $deviceName ($macAddress), RSSI: $rssi")
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "处理扫描结果异常", e)
            }
        }
        
        override fun onScanFailed(errorCode: Int) {
            Log.e(TAG, "扫描失败，错误码: $errorCode")
            isScanning = false
            eventListener?.onScanFailed(errorCode, "扫描失败，错误码: $errorCode")
        }
    }
    
    /**
     * Function: 判断是否为呼吸家设备
     * Parameter: deviceName - 设备名称
     * Return: Boolean - 是否为目标设备
     * Note: 根据设备名称判断是否为呼吸家设备，支持IMEI格式识别
     */
    private fun isRespiratoryDevice(deviceName: String?): Boolean {
        if (deviceName.isNullOrBlank()) return false
        
        val name = deviceName.lowercase()
        
        // 检查是否包含呼吸家相关关键词
        val hasKeyword = BluetoothConstants.DEVICE_NAME_PREFIXES.any { prefix ->
            name.contains(prefix.lowercase())
        }
        
        // 检查是否符合呼吸家设备IMEI格式（10位字符，通常以A或B开头）
        val isImeiFormat = deviceName.length == 10 && 
                          (deviceName.startsWith("A", ignoreCase = true) || 
                           deviceName.startsWith("B", ignoreCase = true)) &&
                          deviceName.substring(1).all { it.isDigit() }
        
        Log.d(TAG, "设备识别检查: $deviceName, 关键词匹配: $hasKeyword, IMEI格式: $isImeiFormat")
        
        return hasKeyword || isImeiFormat
    }
    
    /**
     * Function: 连接设备
     * Parameter: device - 要连接的设备
     * Parameter: autoReconnect - 是否自动重连
     * Note: 建立与指定设备的GATT连接
     */
    fun connectDevice(device: BluetoothDevice, autoReconnect: Boolean = true) {
        if (!isBluetoothAvailable()) {
            eventListener?.onConnectionFailed(device, -1, "蓝牙不可用")
            return
        }
        
        if (!hasRequiredPermissions()) {
            eventListener?.onConnectionFailed(device, -2, "缺少必要权限")
            return
        }
        
        try {
            val androidDevice = bluetoothAdapter?.getRemoteDevice(device.macAddress)
            if (androidDevice == null) {
                eventListener?.onConnectionFailed(device, -3, "无法获取远程设备")
                return
            }
            
            // 创建连接信息
            val connectionInfo = ConnectionInfo(
                connectionId = generateConnectionId(),
                deviceId = device.deviceId,
                state = ConnectionState.CONNECTING,
                autoReconnect = autoReconnect
            )
            
            connectionInfoMap[device.deviceId] = connectionInfo
            eventListener?.onConnectionStateChanged(connectionInfo)
            
            // 建立GATT连接
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                val gatt = androidDevice.connectGatt(context, autoReconnect, gattCallback)
                connectedDevices[device.deviceId] = gatt
                
                Log.d(TAG, "开始连接设备: ${device.deviceName} (${device.macAddress})")
                Log.d(TAG, "设备类型: ${if (device.isRespiratoryDevice()) "呼吸家设备" else "标准BLE设备"}")
                Log.d(TAG, "自动重连: $autoReconnect, 连接ID: ${connectionInfo.connectionId}")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "连接设备失败", e)
            eventListener?.onConnectionFailed(device, -4, "连接失败: ${e.message}")
        }
    }
    
    /**
     * GATT回调
     */
    private val gattCallback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
            val deviceId = gatt.device.address
            val connectionInfo = connectionInfoMap[deviceId]
            
            // 首先检查status，如果不是GATT_SUCCESS，表示连接操作失败
            if (status != BluetoothGatt.GATT_SUCCESS) {
                Log.e(TAG, "连接状态变化失败: $deviceId, status=$status, newState=$newState")
                
                // 处理连接失败
                val device = discoveredDevices[deviceId]
                if (device != null) {
                    val errorMessage = getConnectionErrorMessage(status)
                    Log.e(TAG, "连接失败详情: $errorMessage")
                    
                    // 触发连接失败回调
                    eventListener?.onConnectionFailed(device, status, errorMessage)
                    
                    // 更新连接状态为错误
                    connectionInfo?.let { info ->
                        val updatedInfo = info.copy(
                            state = ConnectionState.ERROR,
                            disconnectTime = System.currentTimeMillis()
                        )
                        connectionInfoMap[deviceId] = updatedInfo
                        eventListener?.onConnectionStateChanged(updatedInfo)
                    }
                }
                
                // 清理资源
                connectedDevices.remove(deviceId)
                handshakeStatus.remove(deviceId)
                handshakeJobs[deviceId]?.cancel()
                handshakeJobs.remove(deviceId)
                gatt.close()
                return
            }
            
            // status正常时，处理连接状态变化
            when (newState) {
                BluetoothProfile.STATE_CONNECTED -> {
                    Log.d(TAG, "设备已连接: $deviceId (status=$status)")
                    
                    // 更新连接状态
                    connectionInfo?.let { info ->
                        val updatedInfo = info.copy(state = ConnectionState.CONNECTED)
                        connectionInfoMap[deviceId] = updatedInfo
                        eventListener?.onConnectionStateChanged(updatedInfo)
                        
                        // 查找设备信息并通知
                        val device = discoveredDevices[deviceId]
                        if (device != null) {
                            eventListener?.onDeviceConnected(device, updatedInfo)
                            
                            // 如果是呼吸家设备，初始化握手状态
                            if (device.isRespiratoryDevice()) {
                                Log.d(TAG, "检测到呼吸家设备，准备握手协议: $deviceId")
                                handshakeStatus[deviceId] = false
                            }
                        }
                    }
                    
                    // 发现服务
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        gatt.discoverServices()
                    }
                }
                
                BluetoothProfile.STATE_DISCONNECTED -> {
                    Log.d(TAG, "设备已断开: $deviceId (status=$status)")
                    
                    // 清理握手状态
                    handshakeStatus.remove(deviceId)
                    handshakeJobs[deviceId]?.cancel()
                    handshakeJobs.remove(deviceId)
                    
                    // 更新连接状态
                    connectionInfo?.let { info ->
                        val updatedInfo = info.copy(
                            state = ConnectionState.DISCONNECTED,
                            disconnectTime = System.currentTimeMillis()
                        )
                        connectionInfoMap[deviceId] = updatedInfo
                        eventListener?.onConnectionStateChanged(updatedInfo)
                        
                        // 查找设备信息并通知
                        val device = discoveredDevices[deviceId]
                        if (device != null) {
                            eventListener?.onDeviceDisconnected(device, updatedInfo)
                        }
                        
                        // 处理自动重连
                        if (info.canReconnect()) {
                            coroutineScope.launch {
                                delay(BluetoothConstants.RECONNECT_INTERVAL_MS)
                                device?.let { reconnectDevice(it) }
                            }
                        }
                    }
                    
                    // 清理连接
                    connectedDevices.remove(deviceId)
                    gatt.close()
                }
            }
        }
        
        override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                val deviceId = gatt.device.address
                val services = gatt.services.map { it.uuid.toString() }
                
                Log.d(TAG, "服务发现完成: $deviceId, 服务数量: ${services.size}")
                
                // 详细输出所有发现的服务和特征
                Log.d(TAG, "=== 设备服务详情 ====")
                var customServiceCount = 0
                var writableCharCount = 0
                
                gatt.services.forEachIndexed { index, service ->
                    val isStandardService = isStandardBluetoothService(service.uuid.toString())
                    val serviceType = if (isStandardService) "[标准服务]" else "[自定义服务]"
                    
                    if (!isStandardService) {
                        customServiceCount++
                        Log.i(TAG, "🎯 发现自定义服务 $customServiceCount: ${service.uuid}")
                    }
                    
                    Log.d(TAG, "服务 $index: ${service.uuid} $serviceType")
                    
                    service.characteristics.forEachIndexed { charIndex, characteristic ->
                        val properties = mutableListOf<String>()
                        val canRead = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_READ) != 0
                        val canWrite = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0
                        val canWriteNoResponse = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0
                        val canNotify = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0
                        val canIndicate = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0
                        
                        if (canRead) properties.add("READ")
                        if (canWrite) properties.add("WRITE")
                        if (canWriteNoResponse) properties.add("WRITE_NO_RESPONSE")
                        if (canNotify) properties.add("NOTIFY")
                        if (canIndicate) properties.add("INDICATE")
                        
                        val isWritable = canWrite || canWriteNoResponse
                        if (isWritable) {
                            writableCharCount++
                            Log.i(TAG, "✍️ 发现可写特征 $writableCharCount: ${characteristic.uuid} [${properties.joinToString(", ")}]")
                        }
                        
                        Log.d(TAG, "  特征 $charIndex: ${characteristic.uuid} [${properties.joinToString(", ")}]")
                        
                        // 输出描述符信息
                        characteristic.descriptors.forEach { descriptor ->
                            Log.d(TAG, "    描述符: ${descriptor.uuid}")
                        }
                    }
                }
                
                Log.i(TAG, "📊 服务发现总结: 自定义服务=$customServiceCount, 可写特征=$writableCharCount")
                Log.d(TAG, "===================")
                
                // 如果没有找到可写特征，记录警告
                if (writableCharCount == 0) {
                    Log.w(TAG, "⚠️ 警告: 未发现任何可写特征，可能无法发送数据")
                }
                
                eventListener?.onServicesDiscovered(deviceId, services)
                
                // 启用数据通知
                enableDataNotification(gatt)
                
                // 如果是呼吸家设备，开始监听握手协议
                val device = discoveredDevices[deviceId]
                if (device?.isRespiratoryDevice() == true) {
                    Log.d(TAG, "开始监听呼吸家设备握手协议: $deviceId")
                    startHandshakeListener(deviceId)
                }
            } else {
                Log.w(TAG, "服务发现失败: $status")
            }
        }
        
        override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
            val deviceId = gatt.device.address
            val characteristicUuid = characteristic.uuid.toString()
            val data = characteristic.value
            
            Log.d(TAG, "📡 特征值变化: $deviceId")
            Log.d(TAG, "  特征UUID: $characteristicUuid")
            Log.d(TAG, "  数据长度: ${data?.size} 字节")
            
            // 通知原始数据变化
            if (data != null) {
                // 输出原始数据的十六进制和字符串格式
                val hexString = data.joinToString(" ") { "%02X".format(it) }
                val stringData = try {
                    String(data, Charsets.UTF_8)
                } catch (e: Exception) {
                    "[无法解析为UTF-8字符串]"
                }
                
                Log.d(TAG, "  十六进制: $hexString")
                Log.d(TAG, "  字符串: $stringData")
                
                // 检查是否包含呼吸家协议标识
                if (stringData.contains("db_sk_")) {
                    Log.i(TAG, "🎯 检测到呼吸家协议数据: $stringData")
                }
                
                eventListener?.onCharacteristicChanged(deviceId, characteristicUuid, data)
                
                // 检查是否为呼吸家设备
                val device = discoveredDevices[deviceId]
                if (device?.isRespiratoryDevice() == true) {
                    Log.d(TAG, "处理呼吸家设备数据: $deviceId")
                    // 处理呼吸家协议字符串数据
                    handleRespiratoryProtocolData(deviceId, data, gatt)
                } else {
                    Log.d(TAG, "处理标准BLE设备数据: $deviceId")
                    // 处理标准BLE数据
                    val connectionInfo = connectionInfoMap[deviceId]
                    if (connectionInfo != null) {
                        val dataRecord = dataParser.parseRawData(data, deviceId, connectionInfo.connectionId)
                        if (dataRecord != null && dataParser.validateDataIntegrity(dataRecord)) {
                            eventListener?.onDataReceived(dataRecord)
                        }
                    }
                }
            } else {
                Log.w(TAG, "⚠️ 接收到空数据: $deviceId")
            }
        }
    }
    
    /**
     * Function: 启用数据通知
     * Parameter: gatt - GATT连接
     * Note: 启用设备数据特征的通知功能，尝试所有支持通知的特征
     */
    private fun enableDataNotification(gatt: BluetoothGatt) {
        try {
            var notificationEnabled = false
            
            // 遍历所有服务和特征，启用所有支持通知的特征
            gatt.services.forEach { service ->
                Log.d(TAG, "检查服务: ${service.uuid}")
                
                service.characteristics.forEach { characteristic ->
                    val properties = characteristic.properties
                    val supportsNotify = (properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0
                    val supportsIndicate = (properties and BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0
                    
                    if (supportsNotify || supportsIndicate) {
                        Log.d(TAG, "尝试启用通知: 服务=${service.uuid}, 特征=${characteristic.uuid}")
                        
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                            // 启用本地通知
                            val success = gatt.setCharacteristicNotification(characteristic, true)
                            Log.d(TAG, "本地通知设置结果: $success")
                            
                            // 写入描述符以启用远程通知
                            val descriptor = characteristic.getDescriptor(UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG_UUID))
                            if (descriptor != null) {
                                val descriptorValue = if (supportsNotify) {
                                    BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                                } else {
                                    BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
                                }
                                descriptor.value = descriptorValue
                                val writeSuccess = gatt.writeDescriptor(descriptor)
                                Log.d(TAG, "描述符写入结果: $writeSuccess, 类型: ${if (supportsNotify) "NOTIFY" else "INDICATE"}")
                                
                                if (success && writeSuccess) {
                                    notificationEnabled = true
                                    Log.i(TAG, "✅ 通知已启用: ${characteristic.uuid}")
                                }
                            } else {
                                Log.w(TAG, "未找到客户端配置描述符: ${characteristic.uuid}")
                            }
                        }
                    }
                }
            }
            
            if (notificationEnabled) {
                Log.i(TAG, "✅ 至少一个通知特征已启用")
            } else {
                Log.w(TAG, "⚠️ 未能启用任何通知特征")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "启用数据通知失败", e)
        }
    }
    
    /**
     * Function: 重连设备
     * Parameter: device - 要重连的设备
     * Note: 尝试重新连接已断开的设备
     */
    private fun reconnectDevice(device: BluetoothDevice) {
        val connectionInfo = connectionInfoMap[device.deviceId]
        if (connectionInfo?.canReconnect() == true) {
            val updatedInfo = connectionInfo.copy(
                reconnectAttempts = connectionInfo.reconnectAttempts + 1
            )
            connectionInfoMap[device.deviceId] = updatedInfo
            
            Log.d(TAG, "尝试重连设备: ${device.deviceName}, 第${updatedInfo.reconnectAttempts}次")
            connectDevice(device, true)
        }
    }
    
    /**
     * Function: 断开设备连接
     * Parameter: deviceId - 设备ID
     * Note: 主动断开与指定设备的连接
     */
    fun disconnectDevice(deviceId: String) {
        val gatt = connectedDevices[deviceId]
        if (gatt != null) {
            try {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                    gatt.disconnect()
                }
                Log.d(TAG, "断开设备连接: $deviceId")
            } catch (e: Exception) {
                Log.e(TAG, "断开连接失败", e)
            }
        }
    }
    
    /**
     * Function: 发送测量指令
     * Parameter: deviceId - 目标设备ID
     * Parameter: commandCode - 命令码（1-开始测量，2-取消测量）
     * Return: Boolean - 是否发送成功
     * Note: 向呼吸家设备发送测量控制指令（需要握手完成）
     */
    fun sendMeasurementCommand(deviceId: String, commandCode: Int): Boolean {
        val gatt = connectedDevices[deviceId]
        if (gatt == null) {
            Log.e(TAG, "设备未连接，无法发送测量指令: $deviceId")
            return false
        }
        
        // 检查握手状态
        if (handshakeStatus[deviceId] != true) {
            Log.w(TAG, "⚠️ 握手未完成，无法发送测量指令: $deviceId")
            return false
        }
        
        return sendDirectMeasurementCommand(deviceId, commandCode)
    }
    
    /**
     * Function: 直接发送测量指令
     * Parameter: deviceId - 目标设备ID
     * Parameter: commandCode - 命令码（1-开始测量，2-取消测量）
     * Return: Boolean - 是否发送成功
     * Note: 直接向呼吸家设备发送测量控制指令，绕过握手检查
     */
    fun sendDirectMeasurementCommand(deviceId: String, commandCode: Int): Boolean {
        val gatt = connectedDevices[deviceId]
        if (gatt == null) {
            Log.e(TAG, "设备未连接，无法发送测量指令: $deviceId")
            return false
        }
        
        try {
            val device = discoveredDevices[deviceId]
            if (device?.isRespiratoryDevice() != true) {
                Log.e(TAG, "设备不是呼吸家设备，无法发送测量指令: $deviceId")
                return false
            }
            
            // 获取设备IMEI和协议版本
            val imei = device.deviceName ?: deviceId.takeLast(10) // 使用MAC地址后10位作为IMEI
            val protocolVersion = "B8.01" // 默认协议版本
            
            // 生成测量指令
            val command = protocolHandler.generateMeasurementCommand(imei, protocolVersion, commandCode)
            val commandData = command.toByteArray(Charsets.UTF_8)
            
            Log.i(TAG, "🚀 直接发送测量指令: $deviceId")
            Log.d(TAG, "  指令内容: $command")
            Log.d(TAG, "  命令码: $commandCode (${if (commandCode == 1) "开始测量" else "取消测量"})")
            Log.d(TAG, "  IMEI: $imei, 协议版本: $protocolVersion")
            
            // 发送指令
            val success = sendRawData(deviceId, commandData)
            if (success) {
                Log.i(TAG, "✅ 直接测量指令发送成功: $deviceId")
            } else {
                Log.e(TAG, "❌ 直接测量指令发送失败: $deviceId")
            }
            
            return success
            
        } catch (e: Exception) {
            Log.e(TAG, "发送直接测量指令异常: $deviceId", e)
            return false
        }
    }
    
    /**
     * Function: 发送数据到设备
     * Parameter: deviceId - 目标设备ID
     * Parameter: data - 要发送的数据
     * Return: Boolean - 是否发送成功
     * Note: 向指定设备发送数据
     */
    fun sendData(deviceId: String, data: ByteArray): Boolean {
        return sendRawData(deviceId, data)
    }
    
    /**
     * Function: 测试所有可写特征
     * Parameter: deviceId - 目标设备ID
     * Parameter: testData - 测试数据（可选，默认为"TEST"）
     * Return: List<String> - 成功写入的特征UUID列表
     * Note: 调试功能，向所有可写特征发送测试数据，用于识别正确的通信特征
     */
    fun testAllWritableCharacteristics(deviceId: String, testData: String = "TEST"): List<String> {
        val gatt = connectedDevices[deviceId]
        val successfulCharacteristics = mutableListOf<String>()
        
        if (gatt == null) {
            Log.e(TAG, "❌ 设备未连接，无法进行测试: $deviceId")
            return successfulCharacteristics
        }
        
        try {
            val data = testData.toByteArray(Charsets.UTF_8)
            Log.i(TAG, "🧪 开始测试所有可写特征: $deviceId")
            Log.i(TAG, "  测试数据: $testData")
            
            val customServices = gatt.services.filter { !isStandardBluetoothService(it.uuid.toString()) }
            val standardServices = gatt.services.filter { isStandardBluetoothService(it.uuid.toString()) }
            
            var testCount = 0
            
            // 测试自定义服务
            Log.i(TAG, "🎯 测试自定义服务特征...")
            for (service in customServices) {
                Log.d(TAG, "测试服务: ${service.uuid}")
                for (characteristic in service.characteristics) {
                    val canWrite = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0 ||
                                  (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0
                    
                    if (canWrite) {
                        testCount++
                        val writeType = if ((characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) "WRITE" else "WRITE_NO_RESPONSE"
                        Log.d(TAG, "🧪 测试特征 $testCount: ${characteristic.uuid} [$writeType]")
                        
                        try {
                            characteristic.value = data
                            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                                val success = gatt.writeCharacteristic(characteristic)
                                
                                if (success) {
                                    Log.i(TAG, "✅ 测试成功: ${characteristic.uuid}")
                                    successfulCharacteristics.add("${service.uuid}:${characteristic.uuid}")
                                } else {
                                    Log.w(TAG, "❌ 测试失败: ${characteristic.uuid}")
                                }
                                
                                // 等待一段时间再测试下一个特征
                                Thread.sleep(500)
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "测试特征异常: ${characteristic.uuid}", e)
                        }
                    }
                }
            }
            
            // 测试标准服务（如果需要）
            if (successfulCharacteristics.isEmpty()) {
                Log.i(TAG, "📋 自定义服务无可用特征，测试标准服务特征...")
                for (service in standardServices) {
                    Log.d(TAG, "测试服务: ${service.uuid}")
                    for (characteristic in service.characteristics) {
                        val canWrite = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0 ||
                                      (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0
                        
                        if (canWrite) {
                            testCount++
                            val writeType = if ((characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) "WRITE" else "WRITE_NO_RESPONSE"
                            Log.d(TAG, "🧪 测试特征 $testCount: ${characteristic.uuid} [$writeType]")
                            
                            try {
                                characteristic.value = data
                                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                                    val success = gatt.writeCharacteristic(characteristic)
                                    
                                    if (success) {
                                        Log.i(TAG, "✅ 测试成功: ${characteristic.uuid}")
                                        successfulCharacteristics.add("${service.uuid}:${characteristic.uuid}")
                                    } else {
                                        Log.w(TAG, "❌ 测试失败: ${characteristic.uuid}")
                                    }
                                    
                                    // 等待一段时间再测试下一个特征
                                    Thread.sleep(500)
                                }
                            } catch (e: Exception) {
                                Log.e(TAG, "测试特征异常: ${characteristic.uuid}", e)
                            }
                        }
                    }
                }
            }
            
            Log.i(TAG, "🧪 测试完成: 共测试 $testCount 个特征，成功 ${successfulCharacteristics.size} 个")
            if (successfulCharacteristics.isNotEmpty()) {
                Log.i(TAG, "✅ 可用特征列表:")
                successfulCharacteristics.forEach { characteristic ->
                    Log.i(TAG, "  - $characteristic")
                }
            } else {
                Log.w(TAG, "⚠️ 未找到任何可用的写入特征")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "测试所有可写特征异常: $deviceId", e)
        }
        
        return successfulCharacteristics
    }
    
    /**
     * Function: 发送原始数据到设备
     * Parameter: deviceId - 目标设备ID
     * Parameter: data - 要发送的数据
     * Return: Boolean - 是否发送成功
     * Note: 向指定设备发送原始字节数据，优先尝试自定义服务的可写特征
     */
    private fun sendRawData(deviceId: String, data: ByteArray): Boolean {
        val gatt = connectedDevices[deviceId]
        if (gatt == null) {
            Log.e(TAG, "❌ 设备未连接: $deviceId")
            eventListener?.onDataSendFailed(data, deviceId, -1, "设备未连接")
            return false
        }
        
        try {
            Log.d(TAG, "🚀 尝试发送原始数据到设备: $deviceId, 数据长度: ${data.size}")
            val dataString = try {
                String(data, Charsets.UTF_8)
            } catch (e: Exception) {
                "[二进制数据]"
            }
            Log.d(TAG, "  发送内容: $dataString")
            val hexString = data.joinToString(" ") { "%02X".format(it) }
            Log.d(TAG, "  十六进制: $hexString")
            
            // 优先尝试自定义服务的可写特征
            val customServices = gatt.services.filter { !isStandardBluetoothService(it.uuid.toString()) }
            val standardServices = gatt.services.filter { isStandardBluetoothService(it.uuid.toString()) }
            
            Log.d(TAG, "📊 服务统计: 自定义服务=${customServices.size}, 标准服务=${standardServices.size}")
            
            // 先尝试自定义服务
            for (service in customServices) {
                Log.d(TAG, "🎯 尝试自定义服务: ${service.uuid}")
                for (characteristic in service.characteristics) {
                    val canWrite = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0 ||
                                  (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0
                    
                    if (canWrite) {
                        val writeType = if ((characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) "WRITE" else "WRITE_NO_RESPONSE"
                        Log.d(TAG, "✍️ 尝试写入自定义特征: ${characteristic.uuid} [$writeType]")
                        
                        characteristic.value = data
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                            val success = gatt.writeCharacteristic(characteristic)
                            Log.d(TAG, "写入结果: $success")
                            
                            if (success) {
                                Log.i(TAG, "✅ 原始数据发送成功: $deviceId")
                                Log.i(TAG, "  服务: ${service.uuid}")
                                Log.i(TAG, "  特征: ${characteristic.uuid}")
                                Log.i(TAG, "  写入类型: $writeType")
                                eventListener?.onDataSent(data, deviceId)
                                return true
                            } else {
                                Log.w(TAG, "⚠️ 写入失败，继续尝试下一个特征")
                            }
                        }
                    } else {
                        Log.d(TAG, "⏭️ 跳过不可写特征: ${characteristic.uuid}")
                    }
                }
            }
            
            // 如果自定义服务失败，再尝试标准服务
            Log.d(TAG, "🔄 自定义服务尝试完毕，开始尝试标准服务")
            for (service in standardServices) {
                Log.d(TAG, "📋 尝试标准服务: ${service.uuid}")
                for (characteristic in service.characteristics) {
                    val canWrite = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0 ||
                                  (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0
                    
                    if (canWrite) {
                        val writeType = if ((characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) "WRITE" else "WRITE_NO_RESPONSE"
                        Log.d(TAG, "✍️ 尝试写入标准特征: ${characteristic.uuid} [$writeType]")
                        
                        characteristic.value = data
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                            val success = gatt.writeCharacteristic(characteristic)
                            Log.d(TAG, "写入结果: $success")
                            
                            if (success) {
                                Log.i(TAG, "✅ 原始数据发送成功: $deviceId")
                                Log.i(TAG, "  服务: ${service.uuid}")
                                Log.i(TAG, "  特征: ${characteristic.uuid}")
                                Log.i(TAG, "  写入类型: $writeType")
                                eventListener?.onDataSent(data, deviceId)
                                return true
                            } else {
                                Log.w(TAG, "⚠️ 写入失败，继续尝试下一个特征")
                            }
                        }
                    } else {
                        Log.d(TAG, "⏭️ 跳过不可写特征: ${characteristic.uuid}")
                    }
                }
            }
            
            Log.e(TAG, "❌ 所有可写特征尝试完毕，均未成功")
            eventListener?.onDataSendFailed(data, deviceId, -3, "未找到可用的写入特征")
            
        } catch (e: Exception) {
            Log.e(TAG, "发送原始数据异常: $deviceId", e)
            eventListener?.onDataSendFailed(data, deviceId, -4, "发送异常: ${e.message}")
        }
        
        return false
    }
    
    /**
     * Function: 获取已连接的设备列表
     * Return: List<String> - 已连接设备ID列表
     * Note: 返回当前已连接的设备ID列表
     */
    fun getConnectedDevices(): List<String> {
        return connectedDevices.keys.toList()
    }
    
    /**
     * Function: 获取连接信息
     * Parameter: deviceId - 设备ID
     * Return: ConnectionInfo? - 连接信息
     * Note: 获取指定设备的连接状态信息
     */
    fun getConnectionInfo(deviceId: String): ConnectionInfo? {
        return connectionInfoMap[deviceId]
    }
    
    /**
     * Function: 清理资源
     * Note: 释放所有连接和资源
     */
    fun cleanup() {
        try {
            // 停止扫描
            if (isScanning) {
                stopScan()
            }
            
            // 断开所有连接
            connectedDevices.values.forEach { gatt ->
                try {
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        gatt.disconnect()
                        gatt.close()
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "关闭GATT连接异常", e)
                }
            }
            
            // 清理数据
            connectedDevices.clear()
            connectionInfoMap.clear()
            discoveredDevices.clear()
            
            Log.d(TAG, "蓝牙管理器资源清理完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "清理资源异常", e)
        }
    }
    
    /**
     * Function: 启动握手监听器
     * Parameter: deviceId - 设备ID
     * Note: 开始监听呼吸家设备的握手协议请求
     */
    private fun startHandshakeListener(deviceId: String) {
        // 取消之前的握手任务
        handshakeJobs[deviceId]?.cancel()
        
        // 启动新的握手监听任务
        val job = coroutineScope.launch {
            var attempts = 0
            val maxAttempts = 20 // 最多等待60秒（20次 * 3秒）
            
            while (attempts < maxAttempts && handshakeStatus[deviceId] != true) {
                delay(3000) // 等待3秒
                attempts++
                
                Log.d(TAG, "等待呼吸家设备握手请求: $deviceId, 尝试次数: $attempts")
                
                // 检查连接状态
                if (!connectedDevices.containsKey(deviceId)) {
                    Log.w(TAG, "设备已断开连接，停止握手监听: $deviceId")
                    break
                }
            }
            
            if (handshakeStatus[deviceId] != true) {
                Log.w(TAG, "握手超时，未收到设备请求: $deviceId")
                // 可以在这里触发握手失败事件
            }
        }
        
        handshakeJobs[deviceId] = job
        Log.d(TAG, "握手监听器已启动: $deviceId")
    }
    
    /**
     * Function: 处理呼吸家协议数据
     * Parameter: deviceId - 设备ID
     * Parameter: data - 接收到的数据
     * Parameter: gatt - GATT连接
     * Note: 处理呼吸家设备的字符串协议数据
     */
    private fun handleRespiratoryProtocolData(deviceId: String, data: ByteArray, gatt: BluetoothGatt) {
        try {
            val dataString = String(data, Charsets.UTF_8)
            Log.d(TAG, "接收到呼吸家协议数据: $deviceId -> $dataString")
            
            val protocolMessage = protocolHandler.parseProtocolMessage(dataString)
            when (protocolMessage) {
                is HandshakeMessage -> {
                    Log.d(TAG, "收到握手请求: IMEI=${protocolMessage.imei}, 协议版本=${protocolMessage.protocolVersion}")
                    Log.d(TAG, "握手请求详情: 终端类型=${protocolMessage.terminalType}, 渠道=${protocolMessage.channelId}")
                    
                    val response = protocolHandler.generateHandshakeResponse(protocolMessage)
                    val success = sendStringData(deviceId, response, gatt)
                    
                    if (success) {
                        // 标记握手完成
                        handshakeStatus[deviceId] = true
                        // 取消握手监听任务
                        handshakeJobs[deviceId]?.cancel()
                        handshakeJobs.remove(deviceId)
                        
                        Log.i(TAG, "✅ 握手协议完成: $deviceId, 设备IMEI: ${protocolMessage.imei}")
                        Log.d(TAG, "设备现在可以进行数据传输")
                    } else {
                        Log.e(TAG, "❌ 握手响应发送失败: $deviceId")
                    }
                }
                
                is DataReportMessage -> {
                    Log.d(TAG, "收到数据报告: IMEI=${protocolMessage.imei}")
                    Log.d(TAG, "测量数据: PEF=${protocolMessage.pefValue} L/min, FEV1=${protocolMessage.fev1Value} L, FVC=${protocolMessage.fvcValue} L")
                    Log.d(TAG, "患者信息: 性别=${if (protocolMessage.gender == 0) "男" else "女"}, 年龄=${protocolMessage.age}, 身高=${protocolMessage.height}cm, 体重=${protocolMessage.weight}kg")
                    Log.d(TAG, "数据序号: ${protocolMessage.currentDataIndex}/${protocolMessage.totalDataCount}, 时间: ${protocolMessage.dataTime}")
                    
                    val response = protocolHandler.generateDataReportResponse(protocolMessage)
                    val success = sendStringData(deviceId, response, gatt)
                    
                    if (success) {
                        Log.i(TAG, "📊 数据接收成功: $deviceId, PEF=${protocolMessage.pefValue}")
                        // 通知数据接收事件
                        eventListener?.onDataReceived(convertToDataRecord(protocolMessage, deviceId))
                    } else {
                        Log.e(TAG, "❌ 数据响应发送失败: $deviceId")
                    }
                }
                
                is com.example.launibleplugin.protocol.AxDateMessage -> {
                    Log.d(TAG, "收到日期时间数据: 时间=${protocolMessage.timeData}")
                    Log.d(TAG, "日期参数: param1=${protocolMessage.param1}, param2=${protocolMessage.param2}, param3=${protocolMessage.param3}")
                    
                    // 通知新的协议消息事件
                    eventListener?.onProtocolMessageReceived(protocolMessage, deviceId)
                }
                
                is com.example.launibleplugin.protocol.AxFvcMessage -> {
                    Log.d(TAG, "收到FVC测量数据: 测试编号=${protocolMessage.testNumber}, 测试次数=${protocolMessage.testCount}")
                    Log.d(TAG, "肺功能数据: PEF=${protocolMessage.pef}, FEV1=${protocolMessage.fev1}, FVC=${protocolMessage.fvc}")
                    Log.d(TAG, "环境数据: 温度=${protocolMessage.temperature}°C, 湿度=${protocolMessage.humidity}%, 气压=${protocolMessage.pressure}hPa")
                    Log.d(TAG, "生理数据: 心率=${protocolMessage.heartRate}bpm, 血氧=${protocolMessage.oxygenSaturation}%")
                    
                    // 通知新的协议消息事件
                    eventListener?.onProtocolMessageReceived(protocolMessage, deviceId)
                }
                
                null -> {
                    Log.w(TAG, "无法解析的协议数据: $dataString")
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "处理呼吸家协议数据异常", e)
        }
    }
    
    /**
     * Function: 发送字符串数据
     * Parameter: deviceId - 设备ID
     * Parameter: data - 要发送的字符串
     * Parameter: gatt - GATT连接
     * Return: Boolean - 是否发送成功
     * Note: 向设备发送字符串数据，动态查找可写特征
     */
    private fun sendStringData(deviceId: String, data: String, gatt: BluetoothGatt): Boolean {
        try {
            val dataBytes = data.toByteArray(Charsets.UTF_8)
            Log.d(TAG, "🚀 尝试发送字符串数据: $deviceId -> $data")
            
            // 优先尝试自定义服务的可写特征
            val customServices = gatt.services.filter { !isStandardBluetoothService(it.uuid.toString()) }
            val standardServices = gatt.services.filter { isStandardBluetoothService(it.uuid.toString()) }
            
            // 先尝试自定义服务
            for (service in customServices) {
                Log.d(TAG, "🎯 尝试自定义服务: ${service.uuid}")
                for (characteristic in service.characteristics) {
                    val canWrite = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0 ||
                                  (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0
                    
                    if (canWrite) {
                        Log.d(TAG, "✍️ 尝试写入自定义特征: ${characteristic.uuid}")
                        characteristic.value = dataBytes
                        
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                            val success = gatt.writeCharacteristic(characteristic)
                            Log.d(TAG, "写入结果: $success")
                            
                            if (success) {
                                Log.i(TAG, "✅ 字符串数据发送成功: $deviceId, 服务: ${service.uuid}, 特征: ${characteristic.uuid}")
                                eventListener?.onDataSent(dataBytes, deviceId)
                                return true
                            }
                        }
                    }
                }
            }
            
            // 如果自定义服务失败，再尝试标准服务
            for (service in standardServices) {
                Log.d(TAG, "📋 尝试标准服务: ${service.uuid}")
                for (characteristic in service.characteristics) {
                    val canWrite = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE) != 0 ||
                                  (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0
                    
                    if (canWrite) {
                        Log.d(TAG, "✍️ 尝试写入标准特征: ${characteristic.uuid}")
                        characteristic.value = dataBytes
                        
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                            val success = gatt.writeCharacteristic(characteristic)
                            Log.d(TAG, "写入结果: $success")
                            
                            if (success) {
                                Log.i(TAG, "✅ 字符串数据发送成功: $deviceId, 服务: ${service.uuid}, 特征: ${characteristic.uuid}")
                                eventListener?.onDataSent(dataBytes, deviceId)
                                return true
                            }
                        }
                    }
                }
            }
            
            Log.w(TAG, "⚠️ 未找到可写入的特征")
            eventListener?.onDataSendFailed(dataBytes, deviceId, -3, "未找到可写入特征")
            
        } catch (e: Exception) {
            Log.e(TAG, "发送字符串数据异常", e)
            eventListener?.onDataSendFailed(data.toByteArray(), deviceId, -4, "发送异常: ${e.message}")
        }
        
        return false
    }
    
    /**
     * Function: 转换协议消息为数据记录
     * Parameter: message - 协议消息
     * Parameter: deviceId - 设备ID
     * Return: DataRecord - 数据记录对象
     * Note: 将呼吸家协议消息转换为标准数据记录格式
     */
    private fun convertToDataRecord(message: DataReportMessage, deviceId: String): DataRecord {
        val connectionInfo = connectionInfoMap[deviceId]
        return dataParser.createRespiratoryDataRecord(
            deviceId = deviceId,
            connectionId = connectionInfo?.connectionId ?: "",
            pefValue = message.pefValue,
            fev1Value = message.fev1Value,
            fvcValue = message.fvcValue,
            timestamp = System.currentTimeMillis()
        )
    }
    
    /**
     * Function: 生成连接ID
     * Return: String - 唯一连接ID
     * Note: 生成唯一的连接标识符
     */
    private fun generateConnectionId(): String {
        return "conn_${System.currentTimeMillis()}_${(Math.random() * 1000).toInt()}"
    }
    
    /**
     * Function: 获取连接错误消息
     * Parameter: status - 连接状态码
     * Return: String - 错误描述信息
     * Note: 根据GATT状态码返回对应的错误描述
     */
    private fun getConnectionErrorMessage(status: Int): String {
        return when (status) {
            133 -> "连接失败 - GATT错误 (133)"
            135 -> "连接失败 - 设备不可达或已关闭 (135)"
            8 -> "连接超时 (8)"
            19 -> "连接失败 - 设备未找到 (19)"
            22 -> "连接失败 - 设备忙碌 (22)"
            129 -> "连接失败 - GATT内部错误 (129)"
            132 -> "连接失败 - 连接被拒绝 (132)"
            134 -> "连接失败 - 连接丢失 (134)"
            else -> "连接失败 - 未知错误 ($status)"
        }
    }
}